package com.distribute.application.admin.permissions;

import java.util.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import com.distribute.framework.core.web.helper.Utils;
import com.distribute.framework.core.lang.*;
import com.distribute.framework.core.web.node.Export;
import com.distribute.framework.core.lang.Protocol.BeanFormat;
import com.distribute.framework.core.util.Excel;
import com.distribute.framework.core.util.Function;
import com.distribute.framework.core.web.util.*;

import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;

import com.distribute.framework.model.*;
import com.distribute.application.admin.*;
/************CTRL_CODE_INPORT************/
/************CTRL_CODE_INPORT************/

/**
 * 组织部门的Controller
 * @author 飞啊飘啊
 */
@SuppressWarnings({"unchecked","rawtypes"})
@flag("SrvGroup")
@RestController
@Component(value="permissions.SrvGroupController")
public class GroupController{
	
	@limitVal(1)//查看权限
	@flag("stuct")
	@RequestMapping("/admin/permissions/group.list.do")
  	public Protocol list() {
  		try{
  			Protocol protocol = Protocol.create(true,null);
  			setFormDataInfo(protocol,null,null);
  			//处理页面的视图数据，比如显示哪些列，自定义显示列等
			ActionHelper.doPageViewFields(SrvGroup.class);
  			Map<String,Object> params = setDefaultSort(ActionHelper.getQueryFormParams(SrvGroup.class));
			protocol.set("PARAMS",ActionHelper.getQueryFormParams(SrvGroup.class));
			protocol.set("fields", Utils.getRequest("fields"));
			params.put("sgParent",Utils.getLong("sgParent",Utils.parseLong("0")));
			protocol.set("desp",Utils.getLong("desp",0l));
			Integer iPage = Utils.getInteger("page", 0);
			Integer iSize = 65535;
			/************CTRL_BEFORE_LIST************/
			/************CTRL_BEFORE_LIST************/
			Page page = SrvGroup.page(iPage,iSize,params);//调用获取分页
	    	protocol.setPage(page,new BeanFormat<SrvGroup>(){
				public Map format(SrvGroup t) {
					return t.toJSON();
				}
			});
			/************CTRL_AFTER_LIST************/
			/************CTRL_AFTER_LIST************/
			return protocol;
		}catch(DefineException e){
			return Protocol.create(false, e.getMessage(), e.getCode());
		}catch(Exception e){		
			e.printStackTrace();
			LoggerHelper.writeError(e);
			return Protocol.create(false,Utils.or(Utils.config("exception.message"), "系统繁忙，请稍后再试"),"exception");
		}
  	}
  	
  	
  	@limitVal(1)//查看权限
  	@flag("stuct")
  	@RequestMapping("/admin/permissions/group.get.do")
  	public Protocol get() {
  		try{
  			Protocol protocol = Protocol.create(true,null).set("srvGroup",new HashMap());
  			SrvGroup srvGroup = Utils.getObject("", SrvGroup.class);
  			if(srvGroup!=null){
				protocol.set("srvGroup",srvGroup.toJSON());
			}
			Long id=Utils.or(Utils.getLong("id"),Utils.getLong("key"));
			String edittype = Utils.getString("edittype");
			if(id==null){
				Long parenter=Utils.getLong("parenter");
				if(parenter!=null){
					srvGroup = new SrvGroup();
					srvGroup.sgParent(parenter);
					protocol.set("srvGroup",srvGroup.toJSON());
					return protocol;
				}
				setFormDataInfo(protocol,edittype,null);
				protocol.reset(false,null,"args-id-null");
			}else{
				srvGroup=SrvGroup.where.sgId(id).get();
				if(srvGroup==null){
					return protocol.reset(false,"数据不存在","data-not-exist");
				}
				setFormDataInfo(protocol,edittype,srvGroup);
				protocol.set("srvGroup",srvGroup.toJSON());
			}			
			/************CTRL_CODE_GET************/
			/************CTRL_CODE_GET************/
			return protocol;
		}catch(DefineException e){
			return Protocol.create(false, e.getMessage(), e.getCode());
		}catch(Exception e){		
			e.printStackTrace();
			LoggerHelper.writeError(e);
			return Protocol.create(false,Utils.or(Utils.config("exception.message"), "系统繁忙，请稍后再试"),"exception");
		}
  	}
  	  	
  	@limitVal(32)//导入权限
  	@RequestMapping("/admin/permissions/group.inport.do")
  	public Protocol inport(@RequestParam("file") final MultipartFile file) { 
  		try{
			final String requestToken = Utils.getString("srvGroupToken");
			final Date lastToken = Utils.getSession(requestToken);
			if(lastToken==null || (new Date().getTime()-lastToken.getTime())>10000){
				if(requestToken!=null)Utils.setSession(requestToken,new Date());//放入Token时间戳	
				SrvGroup.execute(new Function(){
					public <T> T execute(Object... arg0){
						/************CTRL_BEFOR_INPORT************/
						/************CTRL_BEFOR_INPORT************/
						SrvGroup srvGroup = Utils.getObject("srvGroup", SrvGroup.class);
						Excel excel = null;
						try {
							excel = Excel.parse(file.getInputStream(),file.getOriginalFilename());
						} catch (Exception e1) {
							e1.printStackTrace();
						}
						List<String> header = excel.getHeader(0);
						//检查列头信息是否正确
						{
							String[] array = Utils.getString("inport$").split(",");
							for(int j=0;j<header.size();j++){
								if(!Utils.equals(Utils.trim(array[j]),Utils.trim(header.get(j)))){
									throw new DefineException("列("+j+")头信息不正确");
								}
							}
						}
						List<List<String>> array = excel.getArray(0);
				        for(int i=0;i<array.size();i++){ 
							String[] inports = Utils.getString("inports").split(",");
							String sAll="";
							List<String> item = array.get(i);
				        	for(int j=0;j<inports.length;j++){
				        		try {
				        			sAll+=Utils.trim(item.get(j));
				        			SrvGroup.class.getMethod("set"+Utils.ForMat(inports[j])+"$", String.class).invoke(srvGroup, item.get(j));
				        		} catch (Exception e) {
									e.printStackTrace();
								}
				        	}
				        	if(Utils.empty(sAll))continue;
				        	//设置默认值
							setDefaultValue(srvGroup,"insert");
								/************CTRL_BEFORE_INPORT************/
								/************CTRL_BEFORE_INPORT************/
							try{
								SrvGroup.saveSrvGroup(srvGroup);			
								SrvGroup parentSrvGroup = SrvGroup.getSrvGroupById(srvGroup.getSgParent());//父级节点
								if(parentSrvGroup!=null)
									srvGroup.setSgFamily(parentSrvGroup.getSgFamily()+",#"+srvGroup.getSgId()+"#");
								else
									srvGroup.setSgFamily("#"+srvGroup.getSgId()+"#");
								SrvGroup.updateSrvGroup(srvGroup);
							}catch(Exception ex){
								String strMessage = DefineException.parseException(ex,SrvGroup.class);
								if(strMessage!=null){
									throw new DefineException(strMessage);
								}else{
									throw new DefineException(ex);
								}
							}
							/************CTRL_AFTER_INPORT************/
							/************CTRL_AFTER_INPORT************/
				        }
						//记录操作日志
						LoggerHelper.writeLog(SrvGroup.class,"add","导入了[组织部门]数据",LoginHelper.getUserId(), srvGroup,srvGroup.getSgId());
						return null;
					}
				});
				
			}else{
				throw new DefineException("repeat-submit-error","对不起，请勿重复提交"+(10-((new Date().getTime()-lastToken.getTime())/1000))+"秒后再试");
			}
			/************CTRL_AFTER_INPORT************/
			/************CTRL_AFTER_INPORT************/
			return Protocol.create(true,"添加[组织部门]数据成功");
		}catch(DefineException e){
			return Protocol.create(false, e.getMessage(), e.getCode());
		}catch(Exception e){		
			e.printStackTrace();
			LoggerHelper.writeError(e);
			return Protocol.create(false,Utils.or(Utils.config("exception.message"), "系统繁忙，请稍后再试"),"exception");
		}
  	}
  	
  	@limitVal(2)//查看权限
  	@RequestMapping("/admin/permissions/group.insert.do")
  	public Protocol insert() {
  		try{
			final String requestToken = Utils.getString("srvGroupToken");
			final Date lastToken = Utils.getSession(requestToken);
			if(lastToken==null || (new Date().getTime()-lastToken.getTime())>10000){
				if(requestToken!=null)Utils.setSession(requestToken,new Date());//放入Token时间戳	
				SrvGroup.execute(new Function(){
					public <T> T execute(Object... arg0){
						/************CTRL_BEFOR_INSERT************/
						/************CTRL_BEFOR_INSERT************/
						SrvGroup srvGroup = Utils.getObject("srvGroup", SrvGroup.class);
						//批量插入处理
						String vValue = ""+(srvGroup.getSgName()==null?"":srvGroup.getSgName());
						String sArray[]={""+vValue};
						if(vValue.startsWith("[*]")){
							vValue=vValue.replace("[*]","");
							sArray=vValue.split("[\\s|\u3000|\\u00a0|,]+");		
						}
						for(String sItem:sArray){
							if(!Utils.empty(sItem))
							srvGroup.setSgName(String.valueOf(sItem));
							//设置默认值
							setDefaultValue(srvGroup,"insert");
								/************CTRL_BEFORE_ADD************/
								/************CTRL_BEFORE_ADD************/
							SrvGroup.saveSrvGroup(srvGroup);			
							SrvGroup parentSrvGroup = SrvGroup.getSrvGroupById(srvGroup.getSgParent());//父级节点
							if(parentSrvGroup!=null)
								srvGroup.setSgFamily(parentSrvGroup.getSgFamily()+",#"+srvGroup.getSgId()+"#");
							else
								srvGroup.setSgFamily("#"+srvGroup.getSgId()+"#");
							SrvGroup.updateSrvGroup(srvGroup);
								/************CTRL_AFTER_ADD************/
								/************CTRL_AFTER_ADD************/
						}
						//记录操作日志
						LoggerHelper.writeLog(SrvGroup.class,"add","添加了[组织部门]["+srvGroup.getSgName()+"]",LoginHelper.getUserId(), srvGroup,srvGroup.getSgId());
						return null;
					}
				});
				
			}else{
				throw new DefineException("repeat-submit-error","对不起，请勿重复提交"+(10-((new Date().getTime()-lastToken.getTime())/1000))+"秒后再试");
			}
			/************CTRL_AFTER_INSERT************/
			/************CTRL_AFTER_INSERT************/
			return Protocol.create(true,"添加[组织部门]数据成功");
		}catch(DefineException e){
			return Protocol.create(false, e.getMessage(), e.getCode());
		}catch(Exception e){		
			e.printStackTrace();
			LoggerHelper.writeError(e);
			return Protocol.create(false,Utils.or(Utils.config("exception.message"), "系统繁忙，请稍后再试"),"exception");
		}
  	}
  	
  	@limitVal(4)//修改权限
  	@RequestMapping("/admin/permissions/group.update.do")
  	public Protocol update() {
  		try{
			final String requestToken = Utils.getString("srvGroupToken");
			final Date lastToken = Utils.getSession(requestToken);
			if(lastToken==null || (new Date().getTime()-lastToken.getTime())>10000){
				if(requestToken!=null)Utils.setSession(requestToken,new Date());//放入Token时间戳	
				SrvGroup.execute(new Function(){
					public <T> T execute(Object... arg0){
						/************CTRL_BEFOR_UPDATE************/
						/************CTRL_BEFOR_UPDATE************/
						SrvGroup srvGroup = Utils.getObject("srvGroup", SrvGroup.class);
						SrvGroup oldSrvGroup = null;
						String PARAMS = Utils.getString("PARAMS");
						String ids=Utils.getString("ids");
						if(!Utils.empty(PARAMS)){//根据查询条件批量更新
							Map params = Utils.eval(PARAMS);
							params.put("confirm", 1);
							params.put("definex","1=1");
							SrvGroup.updateSrvGroupByConfirm(ActionHelper.getSetValuesFromModel(srvGroup), params);
							LoggerHelper.writeLog(SrvGroup.class, "update", 
										"批量修改了[组织部门]",
										LoginHelper.getUserId(),LoggerHelper.getUpdateDescription(null,srvGroup,false)
										,null);
							/************CTRL_UPDATE_BY_PARAMS************/
							/************CTRL_UPDATE_BY_PARAMS************/
						}else if(!Utils.empty(ids)){//根据ids批量更新
							Map params = new HashMap();
							params.put("sgIdIn",ids);
							params.put("confirm", 1);
							params.put("definex","1=1");
							SrvGroup.updateSrvGroupByConfirm(ActionHelper.getSetValuesFromModel(srvGroup), params);
							LoggerHelper.writeLog(SrvGroup.class, "update", 
										"批量修改了[组织部门]",
										LoginHelper.getUserId(),LoggerHelper.getUpdateDescription(null,srvGroup,false)
										,null);
							/************CTRL_UPDATE_BY_IDS************/
							/************CTRL_UPDATE_BY_IDS************/
						}else{
							if(Utils.empty(Utils.getString("all"))){//修改对象非空的字段
								oldSrvGroup=SrvGroup.where.sgId(srvGroup.getSgId()).get();
								if(oldSrvGroup==null){
									throw new DefineException("对不起，你没有权限修改当前数据");
								}
								
								SrvGroup.updateSrvGroup$NotNull(srvGroup);
								LoggerHelper.writeLog(SrvGroup.class, "update", 
										"修改了[组织部门]["+oldSrvGroup.getSgName()+"]",
										LoginHelper.getUserId(),LoggerHelper.getUpdateDescription(oldSrvGroup, srvGroup,false)
										,srvGroup.getSgId());
								/************CTRL_UPDATE_NOT_NULL************/
								/************CTRL_UPDATE_NOT_NULL************/
							}else{//修改对象全部字段
								oldSrvGroup=SrvGroup.where.sgId(srvGroup.getSgId()).get();
								if(oldSrvGroup==null){
									throw new DefineException("对不起，你没有权限修改当前数据");
								}
								//设置默认值
								//设置默认值
								setDefaultValue(srvGroup,"update");
								srvGroup.setSgFamily(oldSrvGroup.getSgFamily());		
								
								//从oldSrvGroup同步srvGroup未set过的值
								srvGroup.mergeSet(oldSrvGroup);
										
								SrvGroup.updateSrvGroup(srvGroup);
								LoggerHelper.writeLog(SrvGroup.class, "update", 
										"修改了[组织部门]["+oldSrvGroup.getSgName()+"]",
										LoginHelper.getUserId(),LoggerHelper.getUpdateDescription(oldSrvGroup, srvGroup,true)
										,srvGroup.getSgId());
								/************CTRL_UPDATE_ALL************/
								/************CTRL_UPDATE_ALL************/
							}
						}
						/************CTRL_CODE_UPDATE************/
						/************CTRL_CODE_UPDATE************/
						return null;
					}
				});
				
			}else{
				throw new DefineException("repeat-submit-error","对不起，请勿重复提交"+(10-((new Date().getTime()-lastToken.getTime())/1000))+"秒后再试");
			}
			/************CTRL_AFTER_UPDATE************/
			/************CTRL_AFTER_UPDATE************/
			return Protocol.create(true,"修改[组织部门]数据成功");
		}catch(DefineException e){
			return Protocol.create(false, e.getMessage(), e.getCode());
		}catch(Exception e){		
			e.printStackTrace();
			LoggerHelper.writeError(e);
			return Protocol.create(false,Utils.or(Utils.config("exception.message"), "系统繁忙，请稍后再试"),"exception");
		}
  	}
  	
  	@limitVal(8)//删除权限
  	@RequestMapping("/admin/permissions/group.delete.do")
  	public Protocol delete() {
  		try{
			SrvGroup.execute(new Function(){
				public <T> T execute(Object... arg0){
					Long pid=Utils.getLong("id");
					Long[] ids=new Long[]{pid};
					String strIds=Utils.getString( "ids");
					if(!Utils.empty(strIds) && !strIds.trim().equals("")){//批量删除
						String[] array = strIds.split(",");
						ids=new Long[array.length];
						for(int i=0;i<array.length;i++)
							ids[i]=Long.valueOf(array[i]);
					}
					if(ids.length==0){
						throw new DefineException("args-id-null","参数错误");
					}
					for(Long id:ids){
						SrvGroup srvGroup = null;
						srvGroup=SrvGroup.where.sgId(id).get();
						if(srvGroup==null){
							throw new DefineException("对不起，你没有权限修改当前数据");
						}
						SrvGroup.delete(id);						
						if(srvGroup!=null)//记录操作日志
							LoggerHelper.writeLog(SrvGroup.class,"del","删除了[组织部门]["+srvGroup.getSgName()+"]",LoginHelper.getUserId(), srvGroup);
						/************CTRL_CODE_DEL************/
						/************CTRL_CODE_DEL************/
					}
					return null;
				}
			});
			return Protocol.create(true,"删除操作成功");
		}catch(DefineException e){
			return Protocol.create(false, e.getMessage(), e.getCode());
		}catch(Exception e){		
			e.printStackTrace();
			LoggerHelper.writeError(e);
			return Protocol.create(false,Utils.or(Utils.config("exception.message"), "系统繁忙，请稍后再试"),"exception");
		}
  	}

	@RequestMapping("/admin/permissions/group.query.do")
	public Protocol query(){
		try{
			Map<String,Object> params = setDefaultSort(ActionHelper.getQueryFormParams(SrvGroup.class));
			//获取要查询的数据的父节点，没有默认为0（顶层）
			Long parenter = Utils.getLong("parenter");
			if(parenter==null)parenter=0l;
			String family = Utils.getString("family");//要查询的数据的指纹串
			if(!Utils.empty(family))//如果传入了指纹串,根据指纹串获取parenter值
				parenter = SrvGroup.getSrvGroup(Utils.add("sgFamily", family)).getSgId();
			params.put("sgParent",parenter);
			
			String strTerm=Utils.getString("value");//智能搜索时的参数，一般都是主键后面那个字段
			if(!Utils.empty(strTerm)){
				if(strTerm.toLowerCase().startsWith("id:"))//如果查询条件以id:开头，则按ID查询
					params.put("sgId", strTerm.toLowerCase().replaceFirst("id:", ""));					
				else//按标识查询，模糊查询请带%
				{
					String strDefinex = "";
					strDefinex+=" or sg_name like '%"+strTerm.replaceAll("'", "''")+"%'";
					strDefinex="(2=1 "+strDefinex+")";
					params.put("definex",strDefinex);
				}
			}
			
			Integer iSize = Utils.getInteger("size",100);
			/************CTRL_CODE_QUERY************/
			/************CTRL_CODE_QUERY************/
			
			List<SrvGroup> list = SrvGroup.page(0,iSize,params).getResult();
			
			Boolean bObject=Utils.getBoolean("object",false);//是否需要整个数据对象
			List<Map> result = new java.util.ArrayList();			
			for(SrvGroup srvGroup:list){
				Map map = new HashMap();
				map.put("key",srvGroup.getId().toString());
				map.put("value", Utils.js(srvGroup.getKeyValue()));
				if(bObject==true){
					map.put("object",srvGroup.toJSON());
				}
				map.put("more",true);
				result.add(map);
			}
			if(parenter.longValue()==0){
				Map map = new HashMap();
				map.put("key",0);
				map.put("value","[无]");
				map.put("more",false);
				result.add(map);
			}
			/************CTRL_AFTER_QUERY************/
			/************CTRL_AFTER_QUERY************/
			
			return Protocol.create().setList(result);
		}catch(DefineException e){
			return Protocol.create(false, e.getMessage(), e.getCode());
		}catch(Exception e){		
			e.printStackTrace();
			LoggerHelper.writeError(e);
			return Protocol.create(false,Utils.or(Utils.config("exception.message"), "系统繁忙，请稍后再试"),"exception");
		}
	}
	/************CTRL_DEFINE_CODE************/
	/************CTRL_DEFINE_CODE************/
  	
  	/**获取子项列表**/
	public static Map getItems(){
		Map map = new HashMap();
		/************CTRL_DEFINE_ITEMS************/
		/************CTRL_DEFINE_ITEMS************/
		return map;
	}
  	
  	/**
	* 设置排序
	**/
  	private Map<String,Object> setDefaultSort(Map<String, Object> params) {
		String strAsc=SrvGroup.C.get(Utils.forMat(Utils.getString("asc")));//升序字段
		params.put("asc", strAsc);//放入查询条件
		String strDesc=SrvGroup.C.get(Utils.forMat(Utils.getString("desc")));//降序字段
		params.put("desc",strDesc);//放入查询条件 
		if(Utils.empty(strAsc) && Utils.empty(strDesc))//如果未传入排序字段
			params.put("asc","sg_id");//那么，默认以主键降序，传给Dao层
		return params;
	}
  	/**
	* 设置默认值
	**/
	public void setDefaultValue(SrvGroup srvGroup,String type){
		if(type.equals("insert")){//添加时
			if(srvGroup.getSgStatus()==null)
				srvGroup.setSgStatus((short)1);
		}else if(type.equals("update")){//编辑时
		}
	}
	/**
	* 设置表单信息
	**/
	public void setFormDataInfo(Protocol protocol,String edittype,SrvGroup srvGroup){
		Map model = new HashMap();
		model.put("name","srvGroup");
		model.put("caption","组织部门");
		model.put("type","tree");
		model.put("icon","icon-xietong2");
		model.put("PK","sgId");
		model.put("add",true);
		model.put("update",true);
		model.put("details",true);
		List propertys = new ArrayList();
		List submits = new ArrayList();
		model.put("propertys", propertys);
		model.put("submits", submits);	
		protocol.set("model", model);
		if(Utils.empty(edittype)){
		propertys.add(Utils.add("name","sgStatus").add("cell","coner").add("caption","状　　态").add("input","select").add("primary",false).add("length",2).add("options",new Object[]{Utils.add("text","启用").add("value","1").add("depict","列表值"),Utils.add("text","禁用").add("value","0").add("depict","列表值")}));  
		}
		else{
			if(!(edittype.equals("details")?"readonly":(edittype.equals("insert")?"editable":"editable")).equals("none")){
				propertys.add(Utils.add("name","sgName").add("caption","组 名 称").add("input","text").add("primary",false).add("length",32).add("notNull",true).add("unique",false).add("editable",edittype.equals("details")?"readonly":(edittype.equals("insert")?"editable":"editable")));
			}
			if(!(edittype.equals("details")?"readonly":(edittype.equals("insert")?"editable":"editable")).equals("none")){
				propertys.add(Utils.add("name","sgParent").add("caption","上 级 组").add("input","tree").add("primary",false).add("length",8).add("notNull",true).add("unique",false).add("editable",edittype.equals("details")?"readonly":(edittype.equals("insert")?"editable":"editable")).add("relate","SrvGroup"));
			}
			if(!(edittype.equals("details")?"readonly":(edittype.equals("insert")?"none":"editable")).equals("none")){
				propertys.add(Utils.add("name","sgUser").add("caption","负 责 人").add("input","combox").add("primary",false).add("length",8).add("notNull",false).add("unique",true).add("editable",edittype.equals("details")?"readonly":(edittype.equals("insert")?"none":"editable")).add("relate","SrvUser"));
			}
			if(!(edittype.equals("details")?"readonly":(edittype.equals("insert")?"editable":"editable")).equals("none")){
				propertys.add(Utils.add("name","sgFlag").add("caption","组 标 识").add("input","text").add("primary",false).add("length",32).add("notNull",false).add("unique",false).add("editable",edittype.equals("details")?"readonly":(edittype.equals("insert")?"editable":"editable")));
			}
			if(!(edittype.equals("details")?"readonly":(edittype.equals("insert")?"none":"editable")).equals("none")){
				propertys.add(Utils.add("name","sgStatus").add("caption","状　　态").add("input","select").add("primary",false).add("length",2).add("notNull",true).add("unique",false).add("editable",edittype.equals("details")?"readonly":(edittype.equals("insert")?"none":"editable")).add("options",new Object[]{Utils.add("text","启用").add("value","1").add("depict","列表值"),Utils.add("text","禁用").add("value","0").add("depict","列表值")}));
			}
			submits.add(Utils.add("name","submiter").add("value","完成").add("title","完成").add("icon","icon-weibiaoti8"));
		}
	}
  
}